# -*- coding: utf-8 -*-
########################################################################
#  Searx-Qt - Lightweight desktop application for Searx.
#  Copyright (C) 2020-2022  CYBERDEViL
#
#  This file is part of Searx-Qt.
#
#  Searx-Qt is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Searx-Qt is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
########################################################################


import gettext
import locale
import os
from time import strftime, localtime

from searxqt.core.log import warning


__SYSTEM_LOCALE_FOUND = False


# List all available languages.
Languages = [
    ('de_DE', 'Deutsch'),
    ('nl_NL', 'Nederlands'),
    ('es_ES', 'Español')
]


# Set searx-qt default language
Language = None


# Find system default
defaultLanguage, defaultEncoding = locale.getlocale()


# Set current language to system default if found.
index = 0
for key, name in Languages:
    if defaultLanguage == key:
        Language = Languages[index]
        break
    index += 1


def timeToString(time_, fmt="%a %d %b %Y %H:%M:%S"):
    """
    @param time: Time in seconds to format to string.
    @type time: uint

    @param fmt: Format; see
                https://docs.python.org/3/library/time.html#time.strftime
    @type fmt: str
    """
    if __SYSTEM_LOCALE_FOUND:
        locale.setlocale(locale.LC_TIME, normalize(Language[0]))
    return strftime(fmt, localtime(time_))


def durationMinutesToString(minutes):
    """ Convert minutes to a string. Example:
        3 years 30 days 1 hour 30 minutes

    @param minutes: Minutes to convert to duration string.
    @type minutes: int

    60 * 24 = 1440 minutes in 1 day.
    365 * 1440 = 525600 minutes in 1 year.
    """
    if not minutes:
        return "-"

    oneHour = 60
    oneDay = 1440
    oneYear = 525600
    str_ = [
        _("year"), _("years"),
        _("day"), _("days"),
        _("hour"), _("hours"),
        _("min"), _("mins")
    ]

    returnStr = ""
    years = int(minutes / oneYear)
    if years:
        minutes -= years * oneYear
        returnStr += f"{years} {str_[0] if years == 1 else str_[1]}"

    days = int(minutes / oneDay)
    if days:
        minutes -= days * oneDay
        returnStr += f"{days} {str_[2] if days == 1 else str_[3]}"

    hours = int(minutes / oneHour)
    if hours:
        minutes -= hours * oneHour
        returnStr += f"{hours} {str_[4] if hours == 1 else str_[5]}"

    if minutes:
        returnStr += f"{minutes} {str_[6] if minutes == 1 else str_[7]}"

    return returnStr


def normalize(localeName):
    str_ = locale.normalize(localeName)
    enc = locale.getpreferredencoding(do_setlocale=True)
    str_ = str_.split('.', 1)[0]
    return str_ + "." + enc


def localeTest(normalizedLocaleName):
    try:
        locale.setlocale(locale.LC_TIME, normalizedLocaleName)
    except locale.Error:
        return False
    return True


_ = gettext.gettext
if Language:
    # Set LC_TIME if system locale found.
    __SYSTEM_LOCALE_FOUND = localeTest(
        normalize(Language[0])
    )

    if not __SYSTEM_LOCALE_FOUND:
        warning(f"`{normalize(Language[0])}` not found. " \
                "Cannot translate dates and time.")

    # Set .mo file.
    lang = None

    # First try XDG (~/.local/)
    xdgDataHome = os.getenv('XDG_DATA_HOME')
    if xdgDataHome is not None:
        localeDir = os.path.join(xdgDataHome, 'locale')
        try:
            lang = gettext.translation('searx-qt', localedir=localeDir,
                                       languages=[Language[0]])
        except FileNotFoundError:
            pass

    # Not found, check system locale directory
    if not lang:
        try:
            lang = gettext.translation('searx-qt', languages=[Language[0]])
        except FileNotFoundError:
            pass

    if lang:
        lang.install()
        _ = lang.gettext
    else:
        warning(f"Locale file (.mo) for language `{Language[0]}` not found!")
